use std::sync::Arc;

use ntex::web::types::{Path, State};

use crate::{
    errors::CustomError,
    models::user::{Admin, User},
    AppState,
};

// delete comment by comment id, require admin
pub async fn delete_comment(
    user: User,
    admin: Option<Admin>,
    comment_id: Path<(u32)>,
    state: State<Arc<AppState>>,
) -> Result<String, CustomError> {
    let db_pool = &state.db_pool;

    let comment_id = comment_id.0;
    let user_id = user.id;
    // check current user is admin ?
    let is_admin = admin.is_some();

    let rows_affected = if is_admin {
        sqlx::query!("DELETE FROM comments WHERE id = $1", comment_id as i32)
            .execute(db_pool)
            .await?
    } else {
        sqlx::query!(
            "DELETE FROM comments WHERE id = $1 AND user_id = $2",
            comment_id as i32,
            user_id as i32
        )
        .execute(db_pool)
        .await?;
    }
    .rows_affected();

    if rows_affected == 0 {
        Err(CustomError::NotFound("
    failed to delete comment, maybe provided comment id is incorrect or you are required admin to delete this comment".into()))
    } else {
        Ok("delete commnet success".into())
    }
}
